package com.hyyt.shopjsp.logistics.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hyyt.shopjsp.basic.pojo.BasicArea;
import com.hyyt.shopjsp.basic.pojo.BasicUsers;
import com.hyyt.shopjsp.basic.service.IBasicActorPurviewService;
import com.hyyt.shopjsp.basic.service.IBasicAreaService;
import com.hyyt.shopjsp.common.controller.BaseController;
import com.hyyt.shopjsp.logistics.pojo.ShopCityCourier;
import com.hyyt.shopjsp.logistics.service.IShopCityCourierService;
import com.hyyt.shopjsp.util.common.Page;
import com.hyyt.shopjsp.util.common.ResultMsg;
import com.hyyt.shopjsp.util.common.Utils;
import com.hyyt.shopjsp.util.json.FastJsonUtils;

/**
 * Copyright (c) 2017 ShopJsp. All Rights Reserved.
 * ============================================================================
 * 版权所有 2011 - 今 北京华宇盈通科技有限公司，并保留所有权利。
 * ----------------------------------------------------------------------------
 * 提示：在未取得SHOPJSP商业授权之前，您不能将本软件应用于商业用途，否则SHOPJSP将保留追究的权力。
 * ----------------------------------------------------------------------------
 * 官方网站：http://www.shopjsp.com
 * ============================================================================
 * @author Wang Youchun on 2017/03/20 0024下午 3:28.
 */

@Controller
@RequestMapping("/back/cityCourier")
public class ShopCityCourierController extends BaseController{
	
	private Logger log = Logger.getLogger(ShopCityCourierController.class);
	private String basePath = "/back/cityCourier/";
	@Resource
	private IShopCityCourierService shopCityCourierService;
	@Resource
	private IBasicAreaService basicAreaService;
	/**
	 * 进入同城快递管理
	 * @param param 参数
	 * @return 返回到指定页面
	 */
	@RequestMapping("gotoCityCourierPage")
	public String gotoCityCourierPage(Map<String, Object> param){
		Map<String, Object> params= new HashMap<>();
		params.put("parentId", "0");
		List<BasicArea> provinceList=basicAreaService.queryBasicArea(params);//查询省
		param.put("provinceList", provinceList);
		return basePath+"listCityCourier";
	}

	/**
	 * 查询所有同城快递
	 * @param page 分页对象
	 * @param cityCourierName  同城快递员名称
	 * @param phone 快递员联系电话
	 * @param province 地区省级编码
	 * @param cities  地区市级编码
	 * @param district 地区县级编码
	 */
	@RequestMapping(value="ListCityCourier",method=RequestMethod.POST)
	@ResponseBody
	public void ListCityCourier(Page page,String cityCourierName,String phone,Integer province,Integer cities,Integer district, HttpServletResponse response){
		String responsibleAreas =getResponsibleAreas(province,cities,district);//负责区域
		Map<String, Object> param = new HashMap<>();
		if (Utils.objectIsNotEmpty(cityCourierName)) {//是否检索名称
			param.put("cityCourierName", cityCourierName.trim());
		}
		if (Utils.objectIsNotEmpty(phone)) {//是否检索联系电话
			param.put("phone", phone.trim());
		}
		if (Utils.objectIsNotEmpty(responsibleAreas)) {//是否检索负责区域
			param.put("responsibleAreas", responsibleAreas.trim());
		}
		param.put("sortColumns", "cityCourierId desc");
		int totalRecordCount =shopCityCourierService.countShopCityCourier(param);
		 page.setPageInfo(page.getPageSize(), totalRecordCount, page.getCurrentPage());
		 List<ShopCityCourier> cityCourierList =shopCityCourierService.queryShopCityCourier(param, page.getPageRecordBeginIndex(), page.getPageSize());
		if (cityCourierList != null && cityCourierList.size() > 0) {
			for (int i = 0; i < cityCourierList.size(); i++) {
				String[] areas = cityCourierList.get(i).getResponsibleAreas().split(",");
				if(areas.length==3){
					BasicArea ba = basicAreaService.loadBasicArea(Integer.parseInt(areas[2]));
					cityCourierList.get(i).setResponsibleAreas(ba.getFullName());
				}
			}
		}
		 param.clear();
		 param.put("total", totalRecordCount);// total键 存放总记录数，必须的
		 param.put("rows", cityCourierList);// rows键 存放每页记录 list
		 ResultMsg.create(param, response);  //把内容发送到页面
	}

	/**
     * 根据id获得对象
     *
     * @param id
     */
    @RequestMapping(value = "getCityCourierInfo", method = RequestMethod.POST)
    @ResponseBody
	public ResultMsg getCityCourierInfo(Integer id) {
		if (Utils.objectIsNotEmpty(id)) {
			ShopCityCourier citycourier = shopCityCourierService.loadShopCityCourier(id);
			String[] areas = citycourier.getResponsibleAreas().split(",");
			Map<String, Object> param=new HashMap();
			param.put("parentId", areas[0]);
			List<BasicArea> cityList=basicAreaService.queryBasicArea(param);
			param.clear();
			param.put("parentId", areas[1]);
			List<BasicArea> districtList=basicAreaService.queryBasicArea(param);
			BasicArea district=basicAreaService.loadBasicArea(Integer.parseInt(areas[2]));
			param.clear();
			param.put("cityCourier", citycourier);
			param.put("cityList", cityList);
			param.put("districtList", districtList);
			param.put("district", district);
			return ResultMsg.create(true, null, FastJsonUtils.toJSONString(param));
		}else {
			return ResultMsg.create(false);
		}
	}

    /**
     * 保存或者修改同程快递
     *
     * @param shopCityCourier
     * @return
     */
    @RequestMapping(value = "saveOrUpdateCityCourier", method = RequestMethod.POST)
    @ResponseBody
	public ResultMsg saveOrUpdateCityCourier(ShopCityCourier shopCityCourier,Integer province,Integer cities,Integer district) {
		String responsibleAreas =getResponsibleAreas(province,cities,district);//负责区域
		shopCityCourier.setResponsibleAreas(responsibleAreas);
		if (Utils.objectIsNotEmpty(shopCityCourier)) {
			if (Utils.objectIsEmpty(shopCityCourier.getCityCourierId())) {
				shopCityCourierService.saveShopCityCourier(shopCityCourier);
			} else {
				shopCityCourierService.updateShopCityCourier(shopCityCourier);
			}
			return ResultMsg.create(true);
		}else {
			return ResultMsg.create(false);
		}
	}

	public String getResponsibleAreas(Integer province,Integer cities,Integer district){
		StringBuffer sb=new StringBuffer();//用于组装省市县的字符串编码responsibleAreas，进行数据库查询
		if(Utils.objectIsNotEmpty(province)){
			sb.append(province).append(",");
		}
		if(Utils.objectIsNotEmpty(cities)){
			sb.append(cities).append(",");
		}
		if(Utils.objectIsNotEmpty(district)){
			sb.append(district);
		}
		return sb.toString();
	}

    /**
     * 根据传入的用户id集合（以,隔开的字符串）
     *
     * @param ids
     */
	@RequestMapping(value = "deleteCityCouriers", method = RequestMethod.POST)
	@ResponseBody
	public ResultMsg deleteCityCouriers(String ids) {
		if (Utils.objectIsNotEmpty(ids)) {
			shopCityCourierService.deleteShopCityCourier(Integer.parseInt(ids));
			return ResultMsg.create(true);
		}else {
			return ResultMsg.create(false);
		}
	}

    /**
     * 查询市
     * @param id
     * @param response
     */
	@RequestMapping("findCityList")
	public void findCityList(Integer id,HttpServletResponse response){
		Map<String, Object> param=new HashMap<>();
		param.put("parentId", id);
		List<BasicArea> cityList=basicAreaService.queryBasicArea(param);
		String jsonString = FastJsonUtils.toJSONString(cityList);
		param.clear();
		param.put("cityList", jsonString);
		ResultMsg.create(param, response);  //把内容发送到页面
	}

	/**
	 * 初始化同城快递信息
	 * @param response
	 * @param id
	 * @return
	 */
	@RequestMapping(value="initCityCourier",method=RequestMethod.POST)
	public void initCityCourier(HttpServletResponse response,String id){
		Map<String, Object> params=new HashMap<>();
		params.put("responsibleAreas", id);
		params.put("sortColumns", "cityCourierId desc");
		List<ShopCityCourier> cityCourierList = shopCityCourierService.queryShopCityCourier(params);
		for(int i=0;i<cityCourierList.size();i++){
			String[] areas = cityCourierList.get(i).getResponsibleAreas().split(",");
			BasicArea district= basicAreaService.loadBasicArea(Integer.parseInt(areas[2]));
			cityCourierList.get(i).setResponsibleAreas(district.getFullName());
		}
		params.clear();
		params.put("cityCourierList", cityCourierList);
		ResultMsg.create(params, response);  //把内容发送到页面
	}
}
